package cn.buk.tms.dao;

import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.common.sc.Page;
import cn.buk.tms.entity.order.OrderComment;
import cn.buk.tms.entity.order.OrderComment_;
import jakarta.persistence.criteria.*;
import org.springframework.stereotype.Component;

import jakarta.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yfdai
 *
 */
@Component
@Transactional
public class CommentDaoImpl extends AbstractDao implements CommentDao {

  @Override
  public int create(OrderComment comment) {
    em.persist(comment);

    return comment.getId();
  }

  @Override
  public List<OrderComment> searchComments(int enterpriseId, int orderType, int orderId, CommonSearchCriteria sc) {

    List<OrderComment> results = null;

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OrderComment> cq = cb.createQuery(OrderComment.class);
    Root<OrderComment> root = cq.from(OrderComment.class);
    root.alias("o");

    var predicates0 = getPredicates_searchComments(enterpriseId, orderType, orderId, cb, root);


    cq.where(predicates0.toArray(new Predicate[predicates0.size()]));
    List<Order> orderByes = new ArrayList<>();
    orderByes.add(cb.desc(root.get("id")));

    cq.orderBy(orderByes);

    //计算根据条件查询得出的数据总数
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    Root<OrderComment> countRoot = countQuery.from(OrderComment.class);
    countRoot.alias("o");

    var predicates1 = getPredicates_searchComments(enterpriseId, orderType, orderId, cb, countRoot);


    countQuery.select(cb.count(countRoot)).where(predicates1.toArray(new Predicate[predicates1.size()]));
    Long count = em.createQuery(countQuery).getSingleResult();

    int maxResults = count.intValue();
    if (maxResults > 0) {
      Page page = sc.getPage();
      page.setRowCount(maxResults);

      results = em.createQuery(cq)
              .setFirstResult(page.getFirstPosition())
              .setMaxResults(page.getPageSize()).getResultList();
    }

    if (results == null) {
      results = new ArrayList<>();
    }

    return results;
  }

  private static List<Predicate> getPredicates_searchComments(int enterpriseId, int orderType, int orderId, CriteriaBuilder cb, Root<OrderComment> root) {
    List<Predicate> predicates = new ArrayList<>();

    Predicate predicate = cb.conjunction();
    predicates.add(predicate);

    predicate = cb.equal(root.get(OrderComment_.enterpriseId), enterpriseId);
    predicates.add(predicate);

    predicate = cb.equal(root.get(OrderComment_.orderType), orderType);
    predicates.add(predicate);

    predicate = cb.equal(root.get(OrderComment_.orderId), orderId);
    predicates.add(predicate);
    return predicates;
  }

}
